package it.managerService;



import it.Dao.BooksDao;
import it.domain.User;
import it.domain.UserPageBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author wsx
 * @create 2020-04-20-13:26
 */
@WebServlet("/userInfo")
public class userInfo extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String currentPages = req.getParameter("currentPage");
        String query = req.getParameter("query");
        //System.out.println(query);
        if (currentPages == null || "".equals(currentPages)) {
            currentPages = "1";
        }
        Integer currentPage = Integer.valueOf(currentPages);
        //防止点上一页时越界
        if (currentPage <= 1) {
            currentPage = 1;
        }
        BooksDao booksDao = new BooksDao();
        UserPageBean userPageBean = new UserPageBean();

        //总记录数
        Long totalCount = null;
        if (query == null || "".equals(query)) {
            try {
                totalCount = booksDao.queryUserTotalCount();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            try {
                totalCount = booksDao.queryUserCount(query);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        userPageBean.setTotalCount(totalCount.intValue());
        //每页的记录数
        Integer counts = 8;
        //总页数
        double totalPage = Math.ceil(1.0 * userPageBean.getTotalCount() / counts);
        if (currentPage >= (int) totalPage) {
            currentPage = (int) totalPage;
        }
        userPageBean.setCurrPage(currentPage);
        userPageBean.setTotalPage((int) totalPage);
        List<User> userL = null;
        try {
            userL = booksDao.diplayUserInfo(currentPage, counts);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        List<User> users = null;
        try {
            users = booksDao.queryUser(query, currentPage, counts);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (query == null || "".equals(query)) {
            userPageBean.setUsersList(userL);
        } else {
            userPageBean.setUsersList(users);
        }
        req.setAttribute("query", query);
        req.setAttribute("userPageBean", userPageBean);
        req.getRequestDispatcher("manager_userinfo.jsp").forward(req, resp);
    }
}
